layui.use(['tree', 'util', 'jquery'], function () {
    const tree = layui.tree
        , util = layui.util,
        $ = layui.jquery;

    //获取该角色已拥有权限
    let roleCode = sessionStorage.getItem("roleCodeMethod");
    let rolePms = commonAjax(AUTH_SERVER_URL+'/permission/findPmsByRoleCode', {roleCode: roleCode}, 'get');
    let selectedId = selectedData(rolePms.data);

    //获取功能数据
    let result = commonAjax(AUTH_SERVER_URL+'/permission/findMenuTree', {type: 2}, "get");
    let data = result.data.list;

    //生成树
    tree.render({
        elem: '#permissions'
        , data: data
        , showCheckbox: true
        , id: 'pmsId'
        , isJump: false
    });


    //字符串转化为Object
    let obj = eval('[' + selectedId + ']');
    //设置初始选中数据
    tree.setChecked('pmsId', obj);

    //按钮事件
    util.event('lay-demo', {
        //获取选中数据
        getChecked: function (othis) {
            let checkedData = tree.getChecked('pmsId');
            sendData(checkedData);
        }
        //重置
        , reload: function () {
            tree.reload('pmsId', {});
        }
    });

    /**
     * 发送数据
     * @param data
     */
    function sendData(data) {
        let msg = commonAjax(AUTH_SERVER_URL+"/permission/getMenuTreeData?type=2&roleCode=" + roleCode, JSON.stringify(data), "post");
        if (msg.code = 200) {
            layerMsgTreeOperatingSuccess();
        } else {
            layerMsgOperatingFail();
        }
    }

    /**
     * 获取已拥有权限Id集合
     * @param data
     */
    function selectedData(data) {
        let ids = [];
        if (data.length !== 0) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].id !== 1) {
                    ids += data[i].id + ','
                }
            }
            if (ids.length !== 0) {
                ids = ids.substring(0, ids.lastIndexOf(','));
            }
        }
        return ids;
    }

});